<template>
  <div class="order-detail-container">
    <el-card v-if="loading" class="loading-card">
      <el-skeleton :rows="5" animated />
    </el-card>

    <el-card v-else-if="order" class="order-card">
      <!-- 订单头部信息 -->
      <div class="order-header">
        <h1>订单详情 #{{ order.orderId }}</h1>
        <div class="order-status">
          <el-tag :type="getStatusTagType(order.status)">
            {{ formatStatus(order.status) }}
          </el-tag>
          <el-tag :type="getPaymentTagType(order.paymentStatus)" style="margin-left: 10px">
            {{ formatPaymentStatus(order.paymentStatus) }}
          </el-tag>
        </div>
      </div>

      <!-- 订单基本信息 -->
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="酒店名称">{{ order.hotel.name }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">
          <span class="price">¥{{ order.totalAmount.toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="入住日期">{{ formatDate(order.checkInDate) }}</el-descriptions-item>
        <el-descriptions-item label="离店日期">{{ formatDate(order.checkOutDate) }}</el-descriptions-item>
        <el-descriptions-item label="预订人">{{ order.user.firstName }} {{ order.user.lastName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ order.user.phone }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(order.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="特殊要求">{{ order.specialRequests || '无' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 房型信息 -->
      <div class="room-list">
        <h2>房型信息</h2>
        <el-card v-for="(room, index) in order.rooms" :key="index" class="room-card">
          <div class="room-info">
            <h3>{{ room.roomType.name }}</h3>
            <div class="room-meta">
              <span><el-icon><User /></el-icon> 最多入住: {{ room.roomType.maxOccupancy }}人</span>
              <span><el-icon><OfficeBuilding /></el-icon> 面积: {{ room.roomType.roomSize }}㎡</span>
              <span><el-icon><Bed /></el-icon> 床型: {{ room.roomType.bedType }}</span>
            </div>
            <div class="room-price">
              <span class="current-price">¥{{ room.roomType.basePrice.toFixed(2) }}/晚</span>
              <el-tag v-if="room.roomType.isRefundable" type="success" size="small">可退款</el-tag>
              <el-tag v-else type="danger" size="small">不可退款</el-tag>
            </div>
          </div>
          <div class="room-dates">
            <p>入住: {{ formatDate(room.bookingDetail.checkInDate) }}</p>
            <p>离店: {{ formatDate(room.bookingDetail.checkOutDate) }}</p>
          </div>
        </el-card>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="goBack">返回</el-button>
        <el-button v-if="order.status === 'confirmed'" @click="cancelOrder">取消订单</el-button>
      </div>
    </el-card>

    <el-empty v-else description="订单不存在" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const orderId = route.params.orderId
const order = ref(null)
const loading = ref(true)

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/orders/${orderId}`)
    if (response.data.code === 200) {
      order.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取订单详情失败')
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

// 格式化订单状态
const formatStatus = (status) => {
  const statusMap = {
    'confirmed': '已确认',
    'canceled': '已取消',
    'completed': '已完成'
  }
  return statusMap[status] || status
}

// 格式化支付状态
const formatPaymentStatus = (status) => {
  const statusMap = {
    'paid': '已支付',
    'unpaid': '未支付',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    'confirmed': 'success',
    'canceled': 'danger',
    'completed': 'info'
  }
  return typeMap[status] || ''
}

// 获取支付状态标签类型
const getPaymentTagType = (status) => {
  const typeMap = {
    'paid': 'success',
    'unpaid': 'warning',
    'refunded': 'info'
  }
  return typeMap[status] || ''
}

// 取消订单
const cancelOrder = async () => {
  try {
    await axios.put(`/api/orders/${orderId}/cancel`)
    ElMessage.success('订单已取消')
    fetchOrderDetail() // 刷新数据
  } catch (error) {
    ElMessage.error('取消订单失败: ' + error.response?.data?.message || error.message)
  }
}

// 返回
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.room-list {
  margin-top: 30px;
}

.room-card {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.room-info {
  flex: 2;
}

.room-meta {
  margin: 10px 0;
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 14px;
}

.room-meta span {
  display: flex;
  align-items: center;
}

.room-meta .el-icon {
  margin-right: 5px;
}

.current-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.room-dates {
  flex: 1;
  text-align: right;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}
</style>